<template>
  <div>
    <van-sticky>
      <div class="chosen-area">
        <van-row class="chosen-area-top">
          <van-col span="17">已选择 {{chosenItems.length}} 项</van-col>
          <van-col span="4">
            <van-button type="info" size="small" @click="onClickCancel">取消</van-button>
          </van-col>
          <van-col span="3">
            <van-button type="primary" size="small" @click="onClickConfirm">确认</van-button>
          </van-col>
        </van-row>
        <div class="chosen-area-items">
          <span v-for="(item,idx) in chosenItems" :key="idx">
            <van-tag
              closeable
              size="medium"
              type="primary"
              color="#7232dd"
              plain
              @close="onClose(item)"
            >{{getEntityShow(item)}}</van-tag>
          </span>
        </div>
      </div>
    </van-sticky>
    <van-tabs v-model="tabIndex" type="card" :before-change="prepareListData">
      <van-tab v-if="selectorShow.user" title="人员">
        <van-search v-model="search" placeholder="请输入名称搜索" />
        <div>
          <!-- <van-dropdown-menu>
            <van-dropdown-item v-model="select1" :options="option1" />
            <van-dropdown-item v-if="select1" v-model="select2" :options="option2" />
            <van-dropdown-item v-if="select1 && select2" v-model="select3" :options="option3" />
          </van-dropdown-menu> -->
          <van-cell>
            <van-row>
              <van-col span="7">
                <span class="table-head">ID</span>
              </van-col>
              <van-col span="7">
                <span class="table-head">姓名</span>
              </van-col>
              <!-- <van-col span="12">
                <span class="table-head">所属组织</span>
              </van-col> -->
            </van-row>
          </van-cell>
          <van-checkbox-group v-model="checkedUserItems" @change="onUserCheckChange">
            <!-- <van-cell-group> -->
            <van-cell
              v-for="(item, index) in userList"
              clickable
              :key="item.id"
              @click="userToggle(index)"
            >
              <van-col span="7">
                <span class="table-content">{{getRoleDetailID(item)}}</span>
              </van-col>
              <van-col span="7">
                <span class="table-content">{{item.name}}</span>
              </van-col>
              <van-col span="1"></van-col>
              <van-col span="11">
                <span class="table-content">{{item.dept}}</span>
              </van-col>
              <template #right-icon>
                <van-checkbox :name="item.id" ref="userCheckboxes" />
              </template>
            </van-cell>
            <!-- </van-cell-group> -->
          </van-checkbox-group>
        </div>
      </van-tab>
      <van-tab v-if="selectorShow.userGroup" title="人员组">
        <van-search v-model="search" placeholder="请输入名称搜索" />
        <div>
          <van-dropdown-menu>
            <van-dropdown-item v-model="select1" :options="option1" />
            <van-dropdown-item v-if="select1" v-model="select2" :options="option2" />
            <van-dropdown-item v-if="select1 && select2" v-model="select3" :options="option3" />
          </van-dropdown-menu>
          <van-cell>
            <van-row>
              <van-col span="3">
                <span class="table-head">ID</span>
              </van-col>
              <van-col span="7">
                <span class="table-head">名称</span>
              </van-col>
              <!-- <van-col span="13">
                <span class="table-head">所属组织</span>
              </van-col> -->
            </van-row>
          </van-cell>
          <van-radio-group v-model="pickedUserGroupItem" @change="onUserGroupPickChange">
            <!-- <van-cell-group> -->
            <van-cell v-for="(item) in userGroupList" clickable :key="item.id">
              <van-col span="3">
                <span class="table-content">{{item.id}}</span>
              </van-col>
              <van-col span="7">
                <span class="table-content">{{item.name}}</span>
              </van-col>
              <van-col span="1"></van-col>
              <van-col span="13">
                <span class="table-content">{{item.dept}}</span>
              </van-col>
              <template #right-icon>
                <van-radio :name="item.id" />
              </template>
            </van-cell>
            <!-- </van-cell-group> -->
          </van-radio-group>
        </div>
      </van-tab>
      <van-tab v-if="selectorShow.device" title="防护设备">
        <van-search v-model="search" placeholder="请输入名称搜索" />
        <div>
          <van-dropdown-menu>
            <van-dropdown-item v-model="select1" :options="option1" @change="SelectDeviceTypeChange"/>
            <!-- <van-dropdown-item v-if="select1" v-model="select2" :options="option2" />
            <van-dropdown-item v-if="select1 && select2" v-model="select3" :options="option3" /> -->
          </van-dropdown-menu>
          <van-cell>
            <van-row>
              <van-col span="4">
                <span class="table-head">ID</span>
              </van-col>
              <van-col span="7">
                <span class="table-head">防护设备名</span>
              </van-col>
              <van-col span="5">
                <span class="table-head">类型</span>
              </van-col>
              <!-- <van-col span="6">
                <span class="table-head">所属组织</span>
              </van-col> -->
            </van-row>
          </van-cell>
          <van-checkbox-group v-model="checkedDeviceItems" @change="onDeviceCheckChange">
            <!-- <van-cell-group> -->
            <van-cell
              v-for="(item, index) in selectDeviceList"
              clickable
              :key="item.id"
              @click="deviceToggle(index)"
            >
              <van-col span="4">
                <span class="table-content">{{item.id}}</span>
              </van-col>
              <van-col span="7">
                <span class="table-content">{{item.name}}</span>
              </van-col>
              <van-col span="5">
                <span class="table-content" v-if="item.deviceType == 2">手持终端</span>
                <span class="table-content" v-else-if="item.deviceType == 3">定位终端</span>
                <span class="table-content" v-else>未知</span>
              </van-col>
              <van-col span="3">
                <span class="table-content">{{item.dept}}</span>
              </van-col>
              <template #right-icon>
                <van-checkbox :name="item.id" ref="deviceCheckboxes" />
              </template>
            </van-cell>
            <!-- </van-cell-group> -->
          </van-checkbox-group>
        </div>
      </van-tab>
      <van-tab v-if="selectorShow.deviceGroup" title="防护设备组">
        <van-search v-model="search" placeholder="请输入名称搜索" />
        <div>
          <van-dropdown-menu>
            <van-dropdown-item v-model="select1" :options="option1" />
            <van-dropdown-item v-if="select1" v-model="select2" :options="option2" />
            <van-dropdown-item v-if="select1 && select2" v-model="select3" :options="option3" />
          </van-dropdown-menu>
          <van-cell>
            <van-row>
              <van-col span="3">
                <span class="table-head">ID</span>
              </van-col>
              <van-col span="7">
                <span class="table-head">名称</span>
              </van-col>
              <!-- <van-col span="13">
                <span class="table-head">所属组织</span>
              </van-col> -->
            </van-row>
          </van-cell>
          <van-radio-group v-model="pickedDeviceGroupItem" @change="onDeviceGroupPickChange">
            <!-- <van-cell-group> -->
            <van-cell v-for="(item) in deviceGroupList" clickable :key="item.id">
              <van-col span="3">
                <span class="table-content">{{item.id}}</span>
              </van-col>
              <van-col span="7">
                <span class="table-content">{{item.name}}</span>
              </van-col>
              <van-col span="1"></van-col>
              <van-col span="13">
                <span class="table-content">{{item.dept}}</span>
              </van-col>
              <template #right-icon>
                <van-radio :name="item.id" />
              </template>
            </van-cell>
            <!-- </van-cell-group> -->
          </van-radio-group>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { createNamespacedHelpers, mapGetters } from 'vuex'
import { addOrUpdateGroup, getUserInfobyPage, getDeviceInfobyPage, getUserGroupInfobyPage, getDeviceGroupInfobyPage } from '../api/userDeviceGroup'
import { convertUserInfoStruct, convertDeviceInfoStruct, convertGroupInfoStruct, getRoleDetailID, getRoleDetailType, getEntityShow } from '../utils/taskUtils'
const taskCreateStore = createNamespacedHelpers('taskCreate')

export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      selectorShow: { user: true, userGroup: true, device: true, deviceGroup: true }, // 注意顺序保持与视图顺序一致，否则index计算会出错
      role: '', // 页面加载时由router指定的当前要选择的成员所属角色
      tabIndex: 0,
      routeQuery: {}, // 页面加载时由router指定的参数
      search: '',
      checkedUserItems: [], // check 多选
      pickedUserGroupItem: 0, // pick 单选
      checkedDeviceItems: [],
      pickedDeviceGroupItem: 0,
      chosenItems: [], // 顶部“已选择xx项”中的items
      select1: 0,
      select2: 0,
      select3: 0,
      option1: [
        { text: '终端类型', value: 0 },
        { text: '手持终端', value: 1 },
        { text: '定位终端', value: 2 }
      ],
      option2: [
        { text: '全部车间', value: 0 },
        { text: '车间1', value: 1 },
        { text: '车间2', value: 2 },
        { text: '车间3', value: 3 }
      ],
      option3: [
        { text: '全部工区', value: 0 },
        { text: '工区1', value: 1 },
        { text: '工区2', value: 2 },
        { text: '工区3', value: 3 },
        { text: '工区4', value: 4 }
      ],
      userList: [],
      deviceList: [],
      selectDeviceList: [],
      userGroupList: [],
      deviceGroupList: []
    }
  },
  computed: {
    ...mapGetters(['orgIds', 'stationIds', 'taskSetting'])
  },
  watch: {},
  created() {
    this.initialRouteQuery(this.$router.currentRoute.query)
    this.setSelectorShow(this.role)
    if (this.role && this.chosenItems) {
      this.setChosenAndChecked(this.chosenItems)
    }
  },
  mounted() {
    this.orgIds = this.taskSetting.defaultOrg
  },
  beforeDestroy() {
    this.setShowCreate(true)
  },
  methods: {
    ...taskCreateStore.mapMutations(['setShowCreate', 'setTaskCreateData']),
    initialRouteQuery(query) {
      this.routeQuery = query
      this.role = query.role
      this.chosenItems = query.chosenItems
    },
    setSelectorShow(role) {
      if (role === 'workLeader' || role === 'manager' || role === 'liaison' || role === 'safeman' || role === 'petrolman' || role === 'trainChecker') {
        this.selectorShow.userGroup = false
        this.selectorShow.deviceGroup = false
      }
    },
    getEntityShow(item) {
      return getEntityShow(item)
    },
    getSelectorNameByIdx(idx) {
      let count = 0
      const keys = Object.keys(this.selectorShow)
      for (let i = 0; i < keys.length; i++) {
        if (this.selectorShow[keys[i]]) {
          if (count === idx) {
            return keys[i]
          } else count++
        }
      }
      return 'none'
    },
    getIdxBySelectorName(selector) {
      let count = 0
      const keys = Object.keys(this.selectorShow)
      for (let i = 0; i < keys.length; i++) {
        if (this.selectorShow[keys[i]]) {
          if (keys[i] === selector) {
            return count
          } else count++
        }
      }
      return 0
    },
    prepareListData(idx) {
      const selector = this.getSelectorNameByIdx(idx)
      if (selector === 'user') {
        if (!this.userList.length) {
          this.getUserInfo(1, 50)
        }
      } else if (selector === 'userGroup') {
        if (!this.userGroupList.length) {
          this.getUserGroupInfo(1, 50)
        }
      } else if (selector === 'device') {
        if (!this.deviceList.length) {
          this.getDeviceInfo(1, 50)
        }
      } else if (selector === 'deviceGroup') {
        if (!this.deviceGroupList.length) {
          this.getDeviceGroupInfo(1, 50)
        }
      }
      return true
    },
    onClickCancel() {
      this.$router.go(-1)
    },
    SelectDeviceTypeChange() {
      var i
      if (this.select1 === 0) {
        this.selectDeviceList = this.deviceList
      } else if (this.select1 === 1) {
        this.selectDeviceList = []
        for (i in this.deviceList) {
          if (parseInt(this.deviceList[i].deviceType) === 2) {
            this.selectDeviceList.push(this.deviceList[i])
          }
        }
      } else if (this.select1 === 2) {
        this.selectDeviceList = []
        for (i in this.deviceList) {
          if (parseInt(this.deviceList[i].deviceType) === 3) {
            this.selectDeviceList.push(this.deviceList[i])
          }
        }
      }
    },
    setChosenAndChecked(data) {
      if (data instanceof Array) {
        const chosenType = this.getChosenType(data)
        // this.chosenItems = Array.from(data, (item) => {
        //   return { type: item.type, id: parseInt(item.id), name: item.name }
        // })
        if (chosenType === 'user') {
          this.checkedUserItems = Array.from(data, (item) => parseInt(item.id))
          // this.tabIndex = 0
        } else if (chosenType === 'userGroup') {
          this.pickedUserGroupItem = data[0].id
          // this.tabIndex = 1
        } else if (chosenType === 'device') {
          this.checkedDeviceItems = Array.from(data, (item) => parseInt(item.id))
          // this.tabIndex = 2
        } else if (chosenType === 'deviceGroup') {
          this.pickedDeviceGroupItem = data[0].id
          // this.tabIndex = 3
        } else {
        }
        this.tabIndex = this.getIdxBySelectorName(chosenType)
        this.prepareListData(this.tabIndex)
      }
    },
    getChosenType(items) {
      if (items.length) {
        return items[0].type
      } else return 'none'
    },
    async onClickConfirm() {
      if (this.chosenItems.length) {
        this.setTaskCreateData({ key: this.role, value: this.chosenItems })
      } else {
        this.setTaskCreateData({ key: this.role, value: [] })
      }
      this.$router.go(-1)
    },
    getRoleDetailID(item) {
      return getRoleDetailID(item)
    },
    getRoleDetailType(item) {
      return getRoleDetailType(item)
    },
    async getUserInfo(page = null, size = null) {
      const msg = await getUserInfobyPage(page, size, this.orgIds)
      if (msg.code === 0) {
        this.userList = Array.from(msg.data.items, (item) => {
          return convertUserInfoStruct(item)
          // return { id: item.userId, name: item.personName ? item.personName : item.userName, company: '工务', department1: '车间1', department2: '工区1' }
        })
      }
    },
    async getUserGroupInfo(page = null, size = null) {
      const msg = await getUserGroupInfobyPage(page, size)
      if (msg.code === 0) {
        this.userGroupList = Array.from(msg.data.items, (item) => convertGroupInfoStruct(item))
      }
      return true
    },
    async getDeviceInfo(page = null, size = null) {
      const msg1 = await getDeviceInfobyPage(page, size, 2, this.orgIds) // 手持终端
      const msg2 = await getDeviceInfobyPage(page, size, 3, this.orgIds) // 定位终端
      if (msg1.code === 0 && msg2.code === 0) {
        const devices = msg1.data.items.concat(msg2.data.items)
        this.deviceList = Array.from(devices, (item) => {
          return convertDeviceInfoStruct(item)
          // return { id: item.deviceId, name: item.deviceName ? item.deviceName : `${item.deviceId}`, deviceType: parseInt(item.deviceType), company: '工务', department1: '车间1', department2: '工区1' }
        })
        this.selectDeviceList = this.deviceList
      }
    },
    async getDeviceGroupInfo(page = null, size = null) {
      const msg = await getDeviceGroupInfobyPage(page, size)
      if (msg.code === 0) {
        this.deviceGroupList = Array.from(msg.data.items, (item) => convertGroupInfoStruct(item))
      }
      return true
    },
    async createGroup(groupType, members, isTemp = 1) {
      const groupMember = Array.from(members, (item) => {
        return { memberId: item }
      })
      return addOrUpdateGroup(groupType, groupMember, isTemp)
    },
    onUserCheckChange(checkedIds) {
      if (checkedIds.length === 1 && this.isClearOld('user', this.chosenItems)) {
        this.clearUnrelCheckAndPick('userId')
        this.$nextTick(() => {
          this.generateChosenItemFromChecked(checkedIds, 'userList')
        })
      } else {
        this.generateChosenItemFromChecked(checkedIds, 'userList')
      }
    },
    onUserGroupPickChange(pickedId) {
      if (pickedId && this.isClearOld('userGroup', this.chosenItems)) {
        this.clearUnrelCheckAndPick('userGroup')
        this.$nextTick(() => {
          this.generateChosenItemFromPicked(pickedId, 'userGroupList')
        })
      } else {
        this.generateChosenItemFromPicked(pickedId, 'userGroupList')
      }
    },
    onDeviceCheckChange(checkedIds) {
      if (checkedIds.length === 1 && this.isClearOld('device', this.chosenItems)) {
        this.clearUnrelCheckAndPick('deviceId')
        this.$nextTick(() => {
          this.generateChosenItemFromChecked(checkedIds, 'deviceList')
        })
      } else {
        this.generateChosenItemFromChecked(checkedIds, 'deviceList')
      }
    },
    onDeviceGroupPickChange(pickedId) {
      if (pickedId && this.isClearOld('deviceGroup', this.chosenItems)) {
        this.clearUnrelCheckAndPick('deviceGroup')
        this.$nextTick(() => {
          this.generateChosenItemFromPicked(pickedId, 'deviceGroupList')
        })
      } else {
        this.generateChosenItemFromPicked(pickedId, 'deviceGroupList')
      }
    },
    // generateChosenItemFromChecked(type, checkedIds, listName) {
    //   this.chosenItems = Array.from(
    //     this[listName].filter((item) => checkedIds.includes(item.id)),
    //     (item) => {
    //       return { id: item.id, name: item.name, type }
    //     }
    //   )
    // },
    // generateChosenItemFromPicked(type, pickedId, listName) {
    //   this.chosenItems = Array.from(
    //     this[listName].filter((item) => pickedId === item.id),
    //     (item) => {
    //       return { id: item.id, name: item.name, type }
    //     }
    //   )
    // },
    generateChosenItemFromChecked(checkedIds, listName) {
      this.chosenItems = this[listName].filter((item) => checkedIds.includes(item.id))
    },
    generateChosenItemFromPicked(pickedId, listName) {
      this.chosenItems = this[listName].filter((item) => pickedId === item.id)
    },
    isClearOld(curType, items) {
      if (items.length) {
        const idx = items.findIndex((item) => item.type !== curType)
        if (idx >= 0) {
          return true
        } else return false
      } else {
        return false
      }
    },
    clearUnrelCheckAndPick(curType) {
      if (curType === 'user') {
        this.pickedUserGroupItem = 0
        this.checkedDeviceItems = []
        this.pickedDeviceGroupItem = 0
      } else if (curType === 'userGroup') {
        this.checkedUserItems = []
        this.checkedDeviceItems = []
        this.pickedDeviceGroupItem = 0
      } else if (curType === 'device') {
        this.checkedUserItems = []
        this.pickedUserGroupItem = 0
        this.pickedDeviceGroupItem = 0
      } else if (curType === 'deviceGroup') {
        this.checkedUserItems = []
        this.pickedUserGroupItem = 0
        this.checkedDeviceItems = []
      } else {
      }
    },
    onClose(item) {
      const chosen = this.chosenItems.filter((element) => element.id !== item.id)
      this.chosenItems = chosen
      if (item.type === 'user') {
        this.checkedUserItems = Array.from(chosen, (element) => element.id)
      } else if (item.type === 'userGroup') {
        if (item.id === this.pickedUserGroupItem) {
          this.pickedUserGroupItem = 0
        }
      } else if (item.type === 'device') {
        this.checkedDeviceItems = Array.from(chosen, (element) => element.id)
      } else if (item.type === 'deviceGroup') {
        if (item.id === this.pickedDeviceGroupItem) {
          this.pickedDeviceGroupItem = 0
        }
      } else {
      }
    },
    userToggle(index) {
      this.$refs.userCheckboxes[index].toggle()
    },
    deviceToggle(index) {
      this.$refs.deviceCheckboxes[index].toggle()
    }
  }
}
</script>

<style lang="less" scoped>
.table-head {
  font-weight: 700;
  font-size: 30px;
}
.table-content {
  font-size: 30px;
}
.chosen-area {
  background-color: #fff;
  opacity: 1;
  padding: 14px;
  .chosen-area-top {
    font-size: 24px;
    align-items: center;
    display: flex;
  }
  .chosen-area-items {
    span {
      margin-right: 8px;
      margin-top: 24px;
      font-size: 24px;
    }
  }
}
</style>
